<style scoped>
.layui-row {
    overflow: hidden;
}

.select-item {
    /*float: left;*/
    text-align: left;
    width: 100%;
    height: auto !important;
    word-break: break-all;
}

.layui-row:after,
.layui-row:before {
    clear: none;
}

.layui-form>>>.layui-form-select {
    z-index: inherit;
}

.department>>>.layui-table td,
.layui-table th {
    padding: 9px 2px;
    white-space: nowrap;
}

select {
    color: #eee
}

option {
    color: #000;
}

.layui-inline {
    padding: 5px 0;
}

.layui-colla-content {
    border-top: none;
}

.layui-colla-title {
    background: none;
    padding-left: 15px !important;
    height: auto;
}

.department>>>.layui-colla-icon {
    left: auto;
    right: 15px !important;
}

.layui-collapse {
    border: 0 !important;
}

/*.department {*/
/*    position: relative;*/
/*}*/
.openicon {
    position: absolute;
    right: 15px;
    top: 10px;
    z-index: 100000;
    border-radius: 50%;
    color: #fff;
    width: 24px;
    text-align: center;
    height: 24px;
    line-height: 24px;
    background: rgba(0, 150, 136, 0.7);
}

.nodata {
    background: #f2f2f2;
    color: #333;
    text-align: center;
    padding: 5px 0;
}

.department>>>.layui-table-cell {
    padding: 0 0 !important;
}

.department>>>.layui-table-box {
    overflow-y: auto;
    overflow-x: auto;
}

.department>>>.layui-table-body {
    overflow: initial;
}

.department>>>.layui-table-header {
    overflow: initial;
}
</style>

<template>
<div class="department">
    <div class="layui-col-lg4 select-item">
        <button style="float: left;" class="layui-btn layui-btn-sm" id="aaa" @click="toPay()">运费支付申请</button>
    </div>
    <form class="layui-form ">
        <div class="layui-col-lg4 select-item">
            <div class="layui-inline" style="width: 160px">
                <input type="text" name="searchStr" id="tidan" placeholder="请输入提单号" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 160px">
                <div class="layui-input-inline">
                    <input type="text" name="time1" class="layui-input" id="test1" placeholder="请选择派车日期" autocomplete="off">
                </div>
            </div>
            <div class="layui-inline" style="width: 160px">
                <div class="layui-input-inline">
                    <input type="text" name="time2" class="layui-input" id="test2" placeholder="请选择拉货日期" autocomplete="off">
                </div>
            </div>
            <div class="layui-inline" style="width: 180px">
                <div class="layui-input-inline">
                    <input type="text" name="time3" class="layui-input" id="test3" placeholder="请选择派船日期(海外订单)" autocomplete="off">
                </div>
            </div>
            <div class="layui-inline" style="width: 140px">
                <select name="companyid" lay-search lay-filter="companyid">
                    <option value="">请选择物流公司</option>
                    <option v-for="(item, index) in wlcompanys" :key="item.guid" :value="item.guid">{{item.name}}</option>
                </select>
            </div>
            <div class="layui-inline" style="width: 110px">
                <select name="status" lay-search lay-filter="status">
                    <option value="">请选择状态</option>
                    <option v-for="(item, index) in statusList" :key="item.dictkey" :value="item.dictkey">{{item.dicttext}}</option>
                </select>
            </div>
            <div class="layui-inline" style="width: 140px">
                <select name="transtype" lay-search>
                    <option value="">请选择物流类型</option>
                    <option value="1">陆运</option>
                    <option value="2">海运</option>
                    <option value="3">快递</option>
                </select>
            </div>
        </div>
            <div class="layui-col-lg4 select-item">
            <div class="layui-inline" style="width: 140px">
                <input type="text" name="startdate" id="startdate" autocomplete="off" placeholder="请选择开始时间" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 140px">
                <input type="text" name="enddate" id="enddate" autocomplete="off" placeholder="请选择结束时间" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 120px">
                <input type="text" id="carcode" placeholder="请输入车牌号" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 140px">
                <input type="text" id="linkcode" placeholder="业务单号(销售/调拨)" class="layui-input key">
            </div>
            <button type="button" class="layui-btn sou" @click="search">搜索</button>
            <!--                    <button type="button" class="layui-btn" @click="exportExcel">导出excel</button>-->
        </div>
    </form>

    <table class="layui-table layui-form" id="wlorders" lay-filter="wlorders"></table>
    <div class="totalbox">
        <div class="total">合计：
            <span><i style="color: red;">{{total}}</i> 单</span>
            <span style="margin-left: 5px;"><i style="color: red;">{{this.toFix2(totalAmount)}}</i> 元</span>
        </div>
    </div>
    <!--        <Pagination :cur="currentPage" :all="totalPage" :callback="turnPage" ></Pagination>-->
</div>
</template>

<script>
import Pagination from '../common/Pagination.vue'
let qs = require('qs');

var table1;
export default {
    name: 'WlExpensesPay',
    components: {
        Pagination
    },
    data() {
        return {
            orders: [],
            currentPage: 1,
            totalPage: 0,
            wlcompanys: [],
            companyid: '',
            statusList: [],
            status: '',
            transtype: '',
            wlinfos: [],
            checkedData: [],
            totalCustomerid: '',
            totalCustomername: '',
            totalOrderids: [],
            totalOrdercodes: [],
            totalAmount: 0,
            totalWeight: 0,
            total: 0,
            totalOrders: []
        }
    },
    mounted() {
        let that = this;
        layui.use('laydate', function () {
            var laydate = layui.laydate;

            //执行一个laydate实例
            laydate.render({
                elem: '#startdate', //指定元素
                // value: that.getNowMonthDate()
            });
            //执行一个laydate实例
            laydate.render({
                elem: '#enddate', //指定元素
                // value: that.getDate(-1)
            });
            //常规用法
            laydate.render({
                elem: '#test1'
            });
            laydate.render({
                elem: '#test2'
            });
            laydate.render({
                elem: '#test3'
            });
        });

        layui.use(['form'], function () {
            var form = layui.form,
                layer = layui.layer;
            form.render();

            form.on('select', function (data) {
                that[data.elem.name] = data.elem.value;
            })
        });

        layui.use('table', function () {
            var table = layui.table;
            //数据表格渲染
            table1 = table.render({
                elem: '#wlorders',
                url: '/wlinfo/SysWlInfo!getWlInfoList.action?functiontype=18',
                response: {
                    statusCode: 'success' //规定成功的状态码，默认：0
                        ,
                    msgName: 'msg' //规定状态信息的字段名称，默认：msg
                },
                cols: [
                    [{
                            type: 'checkbox'
                        }, {
                            field: 'guid',
                            hide: true
                        }, {
                            field: 'customername',
                            title: '公司',
                            width: 200,
                            rowspan: 2,
                            style: 'text-align: left !important;',
                            templet: function (d) {
                                if (d.mainidsea != '') {
                                    return '<span style="padding-left: 15px;">' + d.customername + '</span>';
                                } else {
                                    return d.customername;
                                }
                            }
                        }, {
                            field: 'code',
                            title: '物流单号',
                            width: 100
                        }, {
                            field: 'loadtime',
                            title: '发货时间',
                            width: 60
                        }, {
                            field: 'deliprovince',
                            title: '发货地址/港口',
                            templet: function (d) {
                                return d.deliPort != '' ? d.deliPort : d.deliprovince + d.delicity + d.delidistrict + d.deliaddress;
                            },
                            width: 160
                        }, {
                            field: 'arriprovince',
                            title: '收货地址/港口',
                            templet: function (d) {
                                return d.arriPort != '' ? d.arriPort : d.arriprovince + d.arricity + d.arridistrict + d.arriaddres;
                            },
                            width: 160
                        }, {
                            field: 'typename',
                            title: '类型',
                            width: 50
                        }, {
                            field: 'farepricetype',
                            title: '计价方式',
                            templet: function (d) {
                                return d.farepricetypename;
                            },
                            width: 60
                        }, {
                            field: '',
                            title: '业务单号',
                            templet: function (d) {
                                return that.getLinkcode(d.items);
                            },
                            width: 80
                        },
                        {
                            field: 'liftcode',
                            title: '提单号',
                            width: 60
                        }, {
                            field: 'fareweight',
                            title: '重量(吨)',
                            width: 60
                        }, {
                            field: 'fareprice',
                            title: '单价',
                            width: 50
                        }, {
                            field: 'othercost',
                            title: '其他费用',
                            width: 60
                        }, {
                            field: 'deductamount',
                            title: '扣减费用',
                            width: 60
                        }, {
                            field: 'amount',
                            title: '结算金额',
                            width: 60
                        }, {
                            field: 'carcode',
                            title: '车牌号',
                            width: 80
                        }, {
                            field: 'drivername',
                            title: '承运人',
                            width: 60
                        },
                        {
                            field: 'cargodate',
                            title: '派车日期',
                            width: 100
                        },
                        {
                            field: 'loadtimesea',
                            title: '派船日期',
                            width: 100
                        }, {
                            field: 'loadtime',
                            title: '拉货日期',
                            width: 100
                        }, {
                            field: 'statusname',
                            title: '状态',
                            width: 60
                        }
                        // ,{field:'carcode', title: '车牌号', width: 80}
                        // ,{field:'unloadtime', title: '到货日期', cellMinWidth: 60}
                        // ,{field:'farestatusname', title: '结算状态', cellMinWidth: 60}
                    ]
                ],
                parseData: function (res) {
                    return {
                        "code": 'success', //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.wlinfos.countItem, //解析数据长度
                        "data": res.wlinfos.rows //解析数据列表
                    };
                },
                page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                        ,
                    groups: 5 //只显示 1 个连续页码
                        ,
                    first: false //不显示首页
                        ,
                    last: false //不显示尾页

                },
                done: function (res) {
                    res.data.forEach((item, index) =>{
                        if (item.mainidsea != '') {
                            let tr = $('#wlorders').next('.layui-table-view').find('.layui-table-body tbody tr[data-index="' + index + '"]');
                            tr.css('background-color', '#FFE4C4');
                        }
                    })
                    $('.layui-table-box').css('max-height', $(window).height() - $('#wlorders').offset().top - 80)
                }
            });
            //选择订单计算费用逻辑
            table.on('checkbox(wlorders)', function (obj) {

                if (obj.type == 'all') {
                    let checkedData = table.checkStatus('wlorders').data;
                    if (checkedData.length == 0) {
                        if (that.totalOrderids.length == 0) {
                            return;
                        } else {
                            that.clearTotalData();
                            return;
                        }
                    }
                    if (!that.checkWlUnique(checkedData)) {
                        that.resetTable();
                        that.toast('不能结算不同物流公司的订单！');
                    } else if (!that.checkOrderStatus(checkedData)) {
                        that.resetTable();
                        that.toast('订单非结算状态！');
                    } else {
                        for (let i = 0; i < checkedData.length; i++) {
                            that.setCheckedData(checkedData[i]);
                        }
                    }
                } else {
                    // let checkSettleSta = true;
                    // if (obj.data.wlitems.length > 0) {
                    //     obj.data.wlitems.forEach(item => {
                    //         checkSettleSta = item.status != 16 ? false : checkSettleSta;
                    //     })
                    // }
                    // checkSettleSta = obj.data.status != 16 ? false : checkSettleSta;
                    // if (!checkSettleSta) {
                    if (obj.data.status != 16) {
                        //选中不成功样式设置
                        $(this).prop("checked", false);
                        $('input[name="layTableCheckbox"]').eq(0).prop("checked", false);
                        layui.form.render('checkbox');
                        that.toast('订单非结算状态！');
                    } else if (that.findFromArr(that.checkedData, obj.data.customerid)) {
                        //选中不成功样式设置
                        $(this).prop("checked", false);
                        $('input[name="layTableCheckbox"]').eq(0).prop("checked", false);
                        layui.form.render('checkbox');
                        that.toast('不能结算不同物流公司的订单！');
                    } else {
                        if (obj.checked == true) {
                            that.setCheckedData(obj.data);

                            that.checkedData.push(obj.data);
                        } else {
                            that.setCheckedData(obj.data, 2);
                            that.checkedData = that.checkedData.filter(function (item) {
                                return item.guid != obj.data.guid;
                            })
                        }
                    }
                }
            });

        });

        this.getWlcompanys();
        this.getStatus();
    },
    updated: function () {
        layui.form.render('select');
        layui.form.render();
    },
    methods: {
        getLinkcode: function (items) {
            let linkcodes = '';
            for (let i = 0; i < items.length; i++) {
                linkcodes += items[i].linkcode + ', ';
            }
            return linkcodes != '' ? linkcodes.substr(0, linkcodes.length - 2) : '';
        },
        getItname: function (it) {
            return it == 1 ? '元/车' : '元/吨';
        },
        //获取当前日期
        getDate: function (dayCount = 0) {
            var dd = new Date();
            dd.setDate(dd.getDate() + dayCount); //设置日期
            var y = dd.getFullYear();
            var m = dd.getMonth() + 1; //获取当前月份的日期
            var fullM = m.length == 2 ? m : '0' + m;
            var d = dd.getDate();
            return y + "-" + fullM + "-" + d;
        },
        //获取本月第一天
        getNowMonthDate: function () {
            var date = new Date();
            var year = date.getFullYear() + "";
            var month = (date.getMonth() + 1) + "";
            // 本月第一天日期
            var begin = year + "-" + month + "-01"
            return begin;
        },
        getWlcompanys: function () {
            let that = this;
            this.$post('/sales/Sellform!getWlCompany.action').then(function (response) {
                if (response.data.info != null) {
                    that.wlcompanys = response.data.info;
                    layui.form.render('select');
                } else {
                    this.toastText('获取物流公司数据失败');
                }
            })
            // this.$post('/sales/Customer!list.action', qs.stringify({type: 3})).then(function (response) {
            //     if (response.data.flag == 'success') {
            //         that.wlcompanys = response.data.result.rows;
            //         layui.form.render('select');
            //         //layui.form('select').render();
            //     } else {
            //         this.toast('获取物流公司数据失败')
            //     }
            // })
        },
        getStatus: function () {
            let that = this;
            this.$post('/sales/Sellform!findDict.action', qs.stringify({
                type: 56
            })).then(function (response) {
                if (response.statusText == "OK") {
                    that.statusList = response.data.filter(function (item) {
                        return item.dictkey >= 4;
                    });
                    layui.form.render('select');
                } else {
                    this.toastText('获取状态数据失败');
                }
            })
        },
        search: function () {
            if (this.dateToValue($('#enddate').val()) < this.dateToValue($('#startdate').val())) {
                this.toastText('结束时间须大于起始时间！');
                return;
            }
            let that = this;
            table1.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    customerid: that.companyid,
                    status: that.status,
                    startdate: $('#startdate').val(),
                    enddate: $('#enddate').val(),
                    transtype: that.transtype,
                    carcode: $('#carcode').val(),
                    linkcode: $('#linkcode').val(),
                    loadtimesea: $('#test3').val(), //派船日期相当于拉货日期
                    cargodate: $('#test1').val(), //派车日期1
                    loadtime: $("#test2").val(), //拉货日期
                    liftcode: $('#tidan').val() //提单号like

                }
            });
        },
        exportExcel: function () {
            if (this.dateToValue($('#enddate').val()) < this.dateToValue($('#startdate').val())) {
                this.toastText('结束时间须大于起始时间！');
                return;
            }
            let params = { //设定异步数据接口的额外参数，任意设
                customerid: this.companyid,
                status: this.status,
                startdate: $('#startdate').val(),
                enddate: $('#enddate').val(),
                transtype: this.transtype,
                carcode: $('#carcode').val(),
                linkcode: $('#linkcode').val()
            };
            location.href = "/wlinfo/SysWlInfo!exportSOA.action?" + JSON.stringify(params);
        },
        resetTable: function () {
            $('input[name="layTableCheckbox"]').prop("checked", false);
            this.totalOrderids.filter(item => {
                $('table').find('tr:contains("' + item + '")').find('input[name="layTableCheckbox"]').prop('checked', true);
            })
            layui.form.render('checkbox');
        },
        setCheckedData: function (data, type = 1) {
            let that = this;
            if (type == 1) {
                if (this.totalOrderids.indexOf(data.guid) < 0) {
                    this.totalCustomerid = data.customerid;
                    this.totalCustomername = data.customername;

                    this.totalOrderids.push(data.guid);
                    this.totalOrdercodes.push(data.code);
                    this.totalOrders.push(data);
                    this.total += 1;
                    this.totalAmount += data.amount;
                    this.totalWeight += data.fareweight;
                }
            } else {
                if (this.totalOrderids.indexOf(data.guid) > -1) {
                    if (this.total == 1) {
                        this.totalCustomerid = '';
                        this.totalCustomername = '';
                    }

                    this.totalOrderids = this.totalOrderids.filter(function (item) {
                        return item != data.guid;
                    });
                    this.totalOrdercodes = this.totalOrdercodes.filter(function (item) {
                        return item != data.code;
                    });
                    this.totalOrders = this.totalOrders.filter(function (item) {
                        return item.guid != data.guid;
                    });
                    this.total -= 1;
                    this.totalAmount -= data.amount;
                    this.totalWeight -= data.fareweight;
                }
            }
        },
        clearTotalData: function () {
            this.totalCustomerid = '';
            this.totalCustomername = '';

            this.totalOrderids = [];
            this.totalOrdercodes = [];
            this.totalOrders = [];
            this.total = 0;
            this.totalAmount = 0;
            this.totalWeight = 0;
        },
        toPay: function () {
            if (this.total <= 0) {
                this.toast('请选择物流订单');
                return;
            }
            let that = this;
            layer.confirm('确定要进行运费支付？', function (index) {
                //that.doPay();
                that.$store.commit('setWlorders', that.totalOrders);
                that.$parent.switchPage('WlPayExpensesApply');
                layer.close(index);
            });
        },
        doPay: function () {
            let loader = layui.layer.load();
            let postData = {
                'entity.customerid': this.totalCustomerid,
                'entity.customername': this.totalCustomername,
                'entity.amount': this.totalAmount
            }
            for (let i = 0; i < this.totalOrderids.length; i++) {
                postData['items[' + i + '].wlinfoid'] = this.totalOrderids[i];
                postData['items[' + i + '].wlinfocode'] = this.totalOrdercodes[i];
            }
            this.$post('/wlinfo/Wlsettlement!save.action', qs.stringify(postData)).then(response => {
                if (response.data.msg == "success") {
                    this.toast('结算成功');
                    this.$parent.switchPage('WlPayExpenses');
                } else {
                    this.toast('系统错误');
                }
                layer.close(loader);
            });
        },
        //判断物流公司是否唯一
        checkWlUnique: function (arr) {
            let parr = [];
            for (let i = 0; i < arr.length; i++) {
                parr.push(arr[i].customerid);
            }
            //json数组去重
            for (var i = 0; i < parr.length; i++) {
                for (var j = i + 1; j < parr.length;) {
                    if (parr[i] == parr[j]) {
                        parr.splice(j, 1); //去除重复的对象；
                    } else {
                        j++;
                    }
                }
            }
            return parr.length == 1;
        },
        //判断物流订单状态是否为已结算
        checkOrderStatus: function (arr) {
            let checkSettleSta = true;
            for (var i = 0; i < arr.length; i++) {
                // if (arr[i].wlitems.length > 0) {
                //     arr[i].wlitems.forEach(item => {
                //         checkSettleSta = item.status != 16 ? false : checkSettleSta;
                //     })
                // }
                // checkSettleSta = arr[i].status != 16 ? false : checkSettleSta;
                // if (arr[i].status != 16) {
                //     checkSettleSta = false;
                //     break;
                // }
            }
            return checkSettleSta;
        },
        findFromArr: function (arr, customerid) {
            return arr.some(item => item.customerid != customerid);
        }
    }
}
</script>
